home *** CD-ROM | disk | FTP | other *** search
- Path: news.lpr.carel.fi!usenet
- From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
- Newsgroups: comp.lang.c
- Subject: Re: problems with a linked list
- Date: Thu, 25 Jan 1996 16:57:35 +0200
- Organization: Carelcomp Forest
- Message-ID: <31079A5F.2F6C@cmt.lpr.mail.carel.fi>
- References: <1996Jan25.125329.23499@dcs.warwick.ac.uk>
- NNTP-Posting-Host: renoir.cclahti.carel.fi
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b6a (WinNT; I)
-
- Daniel Castillo Molero wrote:
- >
- > Dear c community
- > I'm having some problems with a small c program which uses pointers
- > and would like to know if any of you could give me a hand.
- > The following program is intended to create a linked list
- > of three integers, inserting each one at the beginning of
- > the current list, and then print the three integers,
- > but when I run it I get a segmentation fault.
- >
- > #include <stdio.h>
- > #include <stdlib.h>
- >
- > struct side
- > {
- > int a;
- > struct side *next;
- > };
- >
- > struct side *i;
- > struct side *first_side;
- > struct side *tmp;
-
- I would replace first_side and tmp with more logical names:
-
- struct side *head = NULL;
- struct side *tail = NULL;
- >
- > /* insert a new element in the list */
- > void store_side(struct side *i, struct side *first_side) {
- > if (first_side == NULL) { first_side = i; first_side->next = NULL; }
-
- Your first_side = i modifies the _parameter_, not the global first_side.
- > else { i->next = first_side; first_side = i; }
- > }
-
- I would write this:
-
- void store_side(struct side *i)
- {
- if (head == NULL) { tail = head = i; tail->next = NULL; }
- else { tail = tail->next = i; tail->next = NULL; }
- }
- >
- > void main(void) {
- >
- > /* insert first element */
- > first_side = NULL;
- > i = malloc(1*sizeof(struct side));
- > (i->a) = 0;
- > store_side(i, first_side);
-
- Replaced by
-
- store_side(i);
- >
- > /* insert second element */
- > i = malloc(1*sizeof(struct side));
- > (i->a) = 1;
- > store_side(i, first_side);
-
- Again:
-
- store_side(i);
- >
- > /* insert third elemenet */
- > i = malloc(1*sizeof(struct side));
- > (i->a) = 2;
- > store_side(i, first_side);
-
- Yet again:
-
- store_side(i);
- >
- > /* print the three elements */
- > tmp = first_side;
- > printf("side: %d \n",tmp->a);
- > while (tmp->next != NULL) {
- > tmp = tmp->next;
- > printf("side: %d \n",tmp->a);
-
- Now this print stuff would become:
-
- struct side *tmp;
-
- for (tmp = head; tmp; tmp = tmp->next)
- printf("side: %d\n", tmp->a);
-
- > }
- >
- > }
- >
- > --------------------------------------------------
- >
- > Any help would be greatly appreciated.
- > --
- > * Daniel Castillo. D.C.Molero@dcs.warwick.ac.uk *
-
-
- HTH,
- AriL
-
- --
- All my opinions are mine and mine alone.
-